package com.cup.jpa.security.handler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.cup.common.encryption.JWTToken;
import com.cup.common.response.ResponseData;
import com.cup.jpa.security.SelfUserDetails;

@Component
public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {

        SelfUserDetails userDetails = (SelfUserDetails) authentication.getPrincipal();
        
        Map<String, String> params = new HashMap<String, String>();
        params.put("username", userDetails.getUsername());
		String jwtToken = JWTToken.CreateToken("_secret",params);
        
        ResponseData<String> responseBody = new ResponseData<>();
        responseBody.init(jwtToken);

        httpServletResponse.getWriter().write(responseBody.toString());
    }
}

